import json
import time
from rag_chain import RAGChain
from text_processor import TextVectorizer

# 配置信息
TEST_FILE_PATH = 'test_search_info.txt'
TEST_PHONE = '13812345678'
EXPECTED_COMPANY = '上海科技发展有限公司'

# 读取测试文件内容
def read_test_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f'Test file content: {content[:100]}...')  # 打印前100个字符
            return content
    except Exception as e:
        print(f'Error reading {file_path}: {e}')
        return None

# 调试向量器查询
def debug_vectorizer_query(vectorizer, query):
    print(f'\n=== Debug Vectorizer Query ===')
    print(f'Query: {query}')
    try:
        # 查看query方法的签名
        print(f'Query method signature: {vectorizer.query.__doc__}')
        # 尝试不带top_k参数调用
        results = vectorizer.query(query)
        print(f'Vectorizer query results: {json.dumps(results, ensure_ascii=False, indent=2)}')
        return results
    except Exception as e:
        print(f'Error in vectorizer query: {e}')
        return None

# 调试RAG链检索
def debug_rag_retrieval(rag_chain, query):
    print(f'\n=== Debug RAG Chain Retrieval ===')
    print(f'Query: {query}')
    try:
        # 调用RAG链的检索方法
        expanded_query = rag_chain.expand_query(query)
        print(f'Expanded query: {expanded_query}')
        documents = rag_chain.retrieve_relevant_documents(expanded_query)
        print(f'Retrieved documents: {json.dumps(documents, ensure_ascii=False, indent=2)}')
        return documents
    except Exception as e:
        print(f'Error in RAG retrieval: {e}')
        return None

# 主函数
def main():
    print(f'Debugging search for phone number {TEST_PHONE}')

    # 读取测试文件
    file_content = read_test_file(TEST_FILE_PATH)
    if not file_content:
        return

    # 初始化向量器和RAG链
    try:
        vectorizer = TextVectorizer()
        rag_chain = RAGChain(vectorizer)
        print('RAG chain initialized')
    except Exception as e:
        print(f'Error initializing RAG chain: {e}')
        return

    # 添加文档到向量器
    try:
        metadata = {'doc_id': 'test_doc'}
        vectorizer.vectorize_and_store(file_content, metadata)
        print('Document added to vectorizer')

        # 查看向量器中的文档和状态
        try:
            print(f'Vectorizer documents: {vectorizer.list_documents()}')
            # 查看向量器的其他属性
            print(f'Vectorizer has {vectorizer.total_documents} total documents')
            print(f'Vocabulary size: {len(vectorizer.vocab)}')
            print(f'Document frequency keys: {list(vectorizer.document_freq.keys())[:10]}...')  # 前10个词
        except Exception as e:
            print(f'Error accessing vectorizer properties: {e}')
    except Exception as e:
        print(f'Error adding document: {e}')
        return

    # 等待索引完成
    time.sleep(2)

    # 调试向量器查询
    vectorizer_results = debug_vectorizer_query(vectorizer, TEST_PHONE)

    # 调试RAG链检索
    rag_documents = debug_rag_retrieval(rag_chain, TEST_PHONE)

    # 执行完整RAG链搜索
    try:
        print(f'\n=== Full RAG Chain Run ===')
        result = rag_chain.run(TEST_PHONE)
        print(f'Full result: {json.dumps(result, ensure_ascii=False, indent=2)}')
    except Exception as e:
        print(f'Error in full RAG run: {e}')

    # 总结
    print('\n=== Summary ===')
    if vectorizer_results and len(vectorizer_results) > 0:
        print('Vectorizer found relevant documents')
    else:
        print('Vectorizer did not find any relevant documents')

    if rag_documents and len(rag_documents) > 0:
        print('RAG chain retrieved documents')
    else:
        print('RAG chain did not retrieve any documents')

if __name__ == '__main__':
    main()